<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import request from '../utils/request'
import { ElMessage } from 'element-plus'

const router = useRouter()

// 表单数据
const bookForm = ref({
  name: '',
  author: '',
  cover: '',
  tags: []
})

// 作者列表
const authors = ref([])
const loading = ref(false)

// 标签列表
const tags = ref([])

// 获取所有标签
const getTags = async () => {
  try {
    const response = await request.get('/api/tags')
    if (response.data.code === 200) {
      tags.value = response.data.data.list.map(tag => ({
        value: tag.id,
        label: tag.tag_name
      }))
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
  }
}

// 搜索作者
const searchAuthors = async (query) => {
  if (query) {
    loading.value = true
    try {
      const response = await request.get('/api/authors/search', {
        params: { keyword: query }
      })
      if (response.data.code === 200) {
        authors.value = response.data.data.map(author => ({
          value: author.name,
          label: author.name
        }))
      }
    } catch (error) {
      console.error('搜索作者失败:', error)
    } finally {
      loading.value = false
    }
  } else {
    authors.value = []
  }
}

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入图书名称', trigger: 'blur' }],
  author: [{ required: true, message: '请选择作者', trigger: 'change' }],
  tags: [{ required: true, message: '请选择标签', trigger: 'change' }]
}

// 保存图书
const formRef = ref(null)
const saveBook = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const response = await request.post('/api/books', {
          book_name: bookForm.value.name,
          book_author: bookForm.value.author,
          book_img: bookForm.value.cover || '',
          tags: bookForm.value.tags
        })
        
        if (response.data.code === 200) {
          ElMessage.success('添加成功')
          router.push('/books')
        }
      } catch (error) {
        console.error('保存图书失败:', error)
        ElMessage.error('保存失败')
      }
    }
  })
}

// 组件挂载时获取标签列表
onMounted(() => {
  getTags()
})
</script>

<template>
  <div class="add-book">
    <div class="page-header">
      <h2>添加图书</h2>
    </div>
    
    <el-form
      ref="formRef"
      :model="bookForm"
      :rules="rules"
      label-width="100px"
      class="book-form"
    >
      <el-form-item label="封面图片">
        <el-input 
          v-model="bookForm.cover" 
          placeholder="请输入图片URL地址（选填）" 
          class="cover-input"
        />
        <div class="cover-preview-container" v-if="bookForm.cover">
          <img :src="bookForm.cover" class="cover-preview" />
        </div>
      </el-form-item>
      
      <el-form-item label="图书名称" prop="name">
        <el-input v-model="bookForm.name" placeholder="请输入图书名称" />
      </el-form-item>
      
      <el-form-item label="作者" prop="author">
        <el-select
          v-model="bookForm.author"
          filterable
          remote
          reserve-keyword
          placeholder="搜索作者"
          :remote-method="searchAuthors"
          :loading="loading"
        >
          <el-option
            v-for="item in authors"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="标签" prop="tags">
        <el-select
          v-model="bookForm.tags"
          multiple
          placeholder="请选择标签"
        >
          <el-option
            v-for="item in tags"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item>
        <el-button type="primary" @click="saveBook">保存</el-button>
        <el-button @click="router.back()">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.add-book {
  padding: 20px;
}

.page-header {
  margin-bottom: 20px;
}

.book-form {
  max-width: 600px;
  margin: 0 auto;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.cover-input {
  width: 100%;
  max-width: 400px;
}

.cover-preview-container {
  margin-top: 10px;
}

.cover-preview {
  width: 178px;
  height: 178px;
  border-radius: 4px;
  object-fit: cover;
  border: 1px solid #dcdfe6;
}
</style>